/************************************************************
 *  * Hyphenate CONFIDENTIAL
 * __________________
 * Copyright (C) 2016 Hyphenate Inc. All rights reserved.
 *
 * NOTICE: All information contained herein is, and remains
 * the property of Hyphenate Inc.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from Hyphenate Inc.
 */

#import "EaseMessageCell.h"


#import "EaseBubbleView+Text.h"
#import "EaseBubbleView+Image.h"
#import "EaseBubbleView+Location.h"
#import "EaseBubbleView+Voice.h"
#import "EaseBubbleView+Video.h"
#import "EaseBubbleView+File.h"
#import "EaseBubbleView+Card.h"
#import "EaseBubbleView+Task.h"
#import "EaseBubbleView+Leave.h"
#import "UIImageView+EMWebCache.h"
#import "EaseEmotionEscape.h"
//转发
#import "EaseBubbleView+TransmitText.h"
#import "HXRuntimeStatus.h"
#import "HXDDUserEntity.h"
#import "EaseSDKHelper.h"
//时间转化：时间戳转换成NSDate
//#import "TimeTool.h"
CGFloat const EaseMessageCellPadding = 10;

NSString *const EaseMessageCellIdentifierRecvText = @"EaseMessageCellRecvText";
NSString *const EaseMessageCellIdentifierRecvLocation = @"EaseMessageCellRecvLocation";
NSString *const EaseMessageCellIdentifierRecvVoice = @"EaseMessageCellRecvVoice";
NSString *const EaseMessageCellIdentifierRecvVideo = @"EaseMessageCellRecvVideo";
NSString *const EaseMessageCellIdentifierRecvImage = @"EaseMessageCellRecvImage";
NSString *const EaseMessageCellIdentifierRecvFile = @"EaseMessageCellRecvFile";

NSString *const EaseMessageCellIdentifierSendText = @"EaseMessageCellSendText";
NSString *const EaseMessageCellIdentifierSendLocation = @"EaseMessageCellSendLocation";
NSString *const EaseMessageCellIdentifierSendVoice = @"EaseMessageCellSendVoice";
NSString *const EaseMessageCellIdentifierSendVideo = @"EaseMessageCellSendVideo";
NSString *const EaseMessageCellIdentifierSendImage = @"EaseMessageCellSendImage";
NSString *const EaseMessageCellIdentifierSendFile = @"EaseMessageCellSendFile";

@interface EaseMessageCell()
{
    EMMessageBodyType _messageType;
}

@property (nonatomic) NSLayoutConstraint *statusWidthConstraint;
@property (nonatomic) NSLayoutConstraint *activtiyWidthConstraint;
@property (nonatomic) NSLayoutConstraint *hasReadWidthConstraint;
@property (nonatomic) NSLayoutConstraint *bubbleMaxWidthConstraint;

@end

@implementation EaseMessageCell

@synthesize statusButton = _statusButton;
@synthesize bubbleView = _bubbleView;
@synthesize hasRead = _hasRead;
@synthesize activity = _activity;

+ (void)initialize
{
    // UIAppearance Proxy Defaults
    EaseMessageCell *cell = [self appearance];
    cell.statusSize = 20;
    cell.activitySize = 20;
    cell.bubbleMaxWidth = 200;
    cell.leftBubbleMargin = UIEdgeInsetsMake(8, 15, 8, 10);
    cell.rightBubbleMargin = UIEdgeInsetsMake(8, 10, 8, 15);
    cell.bubbleMargin = UIEdgeInsetsMake(8, 0, 8, 0);
    
    cell.messageTextFont = systemFont(15);
    cell.messageTextColor = [UIColor blackColor];
    
    cell.messageLocationFont = systemFont(10);
    cell.messageLocationColor = [UIColor whiteColor];
    
    cell.messageVoiceDurationColor = [UIColor grayColor];
    cell.messageVoiceDurationFont = systemFont(12);
    
    cell.messageFileNameColor = [UIColor blackColor];
    cell.messageFileNameFont = systemFont(13);
    cell.messageFileSizeColor = [UIColor grayColor];
    cell.messageFileSizeFont = systemFont(11);
}

- (instancetype)initWithStyle:(UITableViewCellStyle)style
              reuseIdentifier:(NSString *)reuseIdentifier
                        model:(id<IMessageModel>)model
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        _messageType = model.bodyType;
        [self _setupSubviewsWithType:_messageType
                            isSender:model.isSender
                               model:model];
    }
    
    return self;
}

- (BOOL)canBecomeFirstResponder
{
    return YES;
}

#pragma mark - setup subviews

- (void)_setupSubviewsWithType:(EMMessageBodyType)messageType
                      isSender:(BOOL)isSender
                         model:(id<IMessageModel>)model
{
    _statusButton = [[UIButton alloc] init];
    _statusButton.translatesAutoresizingMaskIntoConstraints = NO;
    _statusButton.imageView.contentMode = UIViewContentModeScaleAspectFit;
    [_statusButton setImage:[UIImage imageNamed:@"EaseUIResource.bundle/messageSendFail"] forState:UIControlStateNormal];
    [_statusButton addTarget:self action:@selector(statusAction) forControlEvents:UIControlEventTouchUpInside];
    _statusButton.hidden = YES;
    [self.contentView addSubview:_statusButton];
    
    _bubbleView = [[EaseBubbleView alloc] initWithMargin:isSender?_rightBubbleMargin:_leftBubbleMargin isSender:isSender];
    _bubbleView.translatesAutoresizingMaskIntoConstraints = NO;
    _bubbleView.backgroundColor = [UIColor clearColor];
    [self.contentView addSubview:_bubbleView];
    
    _avatarView = [[UIImageView alloc] init];
    _avatarView.translatesAutoresizingMaskIntoConstraints = NO;
    _avatarView.backgroundColor = [UIColor clearColor];
    _avatarView.clipsToBounds = YES;
    _avatarView.userInteractionEnabled = YES;
    [self.contentView addSubview:_avatarView];
    
    _hasRead = [[UILabel alloc] init];
    _hasRead.translatesAutoresizingMaskIntoConstraints = NO;
    _hasRead.text = NSLocalizedString(@"hasRead", @"Read");
    _hasRead.textAlignment = NSTextAlignmentCenter;
    _hasRead.font = systemFont(12);
    _hasRead.textColor = HXSystemColor;
    _hasRead.hidden = YES;
    [_hasRead sizeToFit];
    [self.contentView addSubview:_hasRead];
    
    _activity = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    _activity.translatesAutoresizingMaskIntoConstraints = NO;
    _activity.backgroundColor = [UIColor clearColor];
    _activity.hidden = YES;
    [self.contentView addSubview:_activity];
    
    if ([self respondsToSelector:@selector(isCustomBubbleView:)] && [self isCustomBubbleView:model]) {
        [self setCustomBubbleView:model];
    } else {
        switch (messageType) {
            case EMMessageBodyTypeText:
            {
                // Card
                if ([model.message valueForKey:@"ext"]) {
                    // 名片
                    if([[model.message valueForKey:@"ext"] valueForKey:@"user_card"]){
                        [_bubbleView setupCardBubbleView];
                    }
                    // 公告    请假    任务
                    else if([[model.message valueForKey:@"ext"] valueForKey:@"robot_msg_type"])
                    {
                        NSString *msg_type =[[model.message valueForKey:@"ext"] valueForKey:@"robot_msg_type"];
                        // announcement 公告  holiday  请假  task  任务
                        if ([msg_type isEqualToString:@"announcement"]
//                            ||[msg_type isEqualToString:@"task"]
                            )
                        {
                            [_bubbleView setupTaskBubbleView];
                        }
//                        else if([msg_type isEqualToString:@"holiday"])
//                        {
//                            // coding
//                            [_bubbleView setupLeaveBubbleView];
//                        }
                    }
                    else if([[model.message valueForKey:@"ext"] valueForKey:@"is_voice_call"] || [[model.message valueForKey:@"ext"] valueForKey:@"is_video_call"])
                    {
                        [_bubbleView setupTextBubbleView];
                        _bubbleView.textLabel.font = _messageTextFont;
                        _bubbleView.textLabel.textColor = _messageTextColor;
                    }
                    //文本转发
                    else if ([[model.message valueForKey:@"ext"] valueForKey:MESSAGE_TRANSMIT]) {
                        [_bubbleView setupTextBubbleView];
                        _bubbleView.textLabel.font = _messageTextFont;
                        _bubbleView.textLabel.textColor = _messageTextColor;
//                        [_bubbleView setupTransmitTextBubbleView];
                    }
                }
                else
                {
                    [_bubbleView setupTextBubbleView];
                    _bubbleView.textLabel.font = _messageTextFont;
                    _bubbleView.textLabel.textColor = _messageTextColor;
                }
            }
                break;
            case EMMessageBodyTypeImage:
            {
                [_bubbleView setupImageBubbleView];
                
                _bubbleView.imageView.image = [UIImage imageNamed:@"EaseUIResource.bundle/imageDownloadFail"];
            }
                break;
            case EMMessageBodyTypeLocation:
            {
                [_bubbleView setupLocationBubbleView];
                
                _bubbleView.locationImageView.image = [[UIImage imageNamed:@"EaseUIResource.bundle/chat_location_preview"] stretchableImageWithLeftCapWidth:10 topCapHeight:10];
                _bubbleView.locationLabel.font = _messageLocationFont;
                _bubbleView.locationLabel.textColor = _messageLocationColor;
            }
                break;
            case EMMessageBodyTypeVoice:
            {
                [_bubbleView setupVoiceBubbleView];
                
                _bubbleView.voiceDurationLabel.textColor = _messageVoiceDurationColor;
                _bubbleView.voiceDurationLabel.font = _messageVoiceDurationFont;
            }
                break;
            case EMMessageBodyTypeVideo:
            {
                [_bubbleView setupVideoBubbleView];
                
                _bubbleView.videoTagView.image = [UIImage imageNamed:@"EaseUIResource.bundle/messageVideo"];
            }
                break;
            case EMMessageBodyTypeFile:
            {
                [_bubbleView setupFileBubbleView];
                
                _bubbleView.fileNameLabel.font = _messageFileNameFont;
                _bubbleView.fileNameLabel.textColor = _messageFileNameColor;
                _bubbleView.fileSizeLabel.font = _messageFileSizeFont;
            }
                break;
            default:
                break;
        }
    }
    [self addHasReadLastMessageViews];
    [self _setupConstraints];
    
    UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(bubbleViewTapAction:)];
    [_bubbleView addGestureRecognizer:tapRecognizer];
    
    UITapGestureRecognizer *tapRecognizer2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(avatarViewTapAction:)];
    [_avatarView addGestureRecognizer:tapRecognizer2];
}

#pragma mark - Setup Constraints

- (void)_setupConstraints
{
    //bubble view
    _oldLastBuddleConstraint = [NSLayoutConstraint constraintWithItem:self.bubbleView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.contentView attribute:NSLayoutAttributeBottom multiplier:1.0 constant:-EaseMessageCellPadding];
    [self addConstraint:_oldLastBuddleConstraint];
    
    self.bubbleMaxWidthConstraint = [NSLayoutConstraint constraintWithItem:self.bubbleView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationLessThanOrEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:self.bubbleMaxWidth];
    [self addConstraint:self.bubbleMaxWidthConstraint];
    //    self.bubbleMaxWidthConstraint.active = YES;
    
    //status button
    self.statusWidthConstraint = [NSLayoutConstraint constraintWithItem:self.statusButton attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:self.statusSize];
    [self addConstraint:self.statusWidthConstraint];
    [self addConstraint:[NSLayoutConstraint constraintWithItem:self.statusButton attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:self.statusButton attribute:NSLayoutAttributeWidth multiplier:1.0 constant:0]];
    [self addConstraint:[NSLayoutConstraint constraintWithItem:self.statusButton attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.contentView attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0]];
    
    //activtiy
    self.activtiyWidthConstraint = [NSLayoutConstraint constraintWithItem:self.activity attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:self.activitySize];
    [self addConstraint:self.activtiyWidthConstraint];
    [self addConstraint:[NSLayoutConstraint constraintWithItem:self.activity attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:self.activity attribute:NSLayoutAttributeWidth multiplier:1.0 constant:0]];
    [self addConstraint:[NSLayoutConstraint constraintWithItem:self.activity attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.contentView attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0]];
    
    [self _updateHasReadWidthConstraint];
    [self addConstraint:[NSLayoutConstraint constraintWithItem:self.hasRead attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.contentView attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0]];
    [self addConstraint:[NSLayoutConstraint constraintWithItem:self.hasRead attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:self.statusButton attribute:NSLayoutAttributeWidth multiplier:1.0 constant:0]];
    //    [self addConstraint:[NSLayoutConstraint constraintWithItem:self.hasRead attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:self.activity attribute:NSLayoutAttributeWidth multiplier:1.0 constant:0]];
}
- (void)addHasReadLastMessageViews {
    
    _hasReadTipsLab = [[UILabel alloc] init];
    _hasReadTipsLab.translatesAutoresizingMaskIntoConstraints = false;
    //    _hasReadTipsLab.backgroundColor = [UIColor colorWithRed:200/255.0 green:200/255.0 blue:200/255.0 alpha:1];
    _hasReadTipsLab.backgroundColor = [UIColor lightGrayColor];
    _hasReadTipsLab.layer.cornerRadius = 10;
    _hasReadTipsLab.clipsToBounds = YES;
    _hasReadTipsLab.text = @"上次看到这里了";
    _hasReadTipsLab.hidden = YES;
    _hasReadTipsLab.textColor = [UIColor whiteColor];
    _hasReadTipsLab.font = systemFont(12);
    _hasReadTipsLab.textAlignment = NSTextAlignmentCenter;
    _hasReadTipsLab.userInteractionEnabled = NO;
    [self addSubview:_hasReadTipsLab];
    
    [self addConstraint:[NSLayoutConstraint constraintWithItem:_hasReadTipsLab attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0]];
    [self addConstraint:[NSLayoutConstraint constraintWithItem:_hasReadTipsLab attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.bubbleView attribute:NSLayoutAttributeBottom multiplier:1.0 constant:5]];
    [self addConstraint:[NSLayoutConstraint constraintWithItem:_hasReadTipsLab attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeLeft multiplier:1.0 constant:16]];
    [self addConstraint:[NSLayoutConstraint constraintWithItem:_hasReadTipsLab attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeRight multiplier:1.0 constant:-16]];
    [self addConstraint:[NSLayoutConstraint constraintWithItem:_hasReadTipsLab attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:20]];
}

#pragma mark - Update Constraint

- (void)_updateHasReadWidthConstraint
{
    if (_hasRead) {
        [self removeConstraint:self.hasReadWidthConstraint];
        
        self.hasReadWidthConstraint = [NSLayoutConstraint constraintWithItem:_hasRead attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:0 constant:40];
        [self addConstraint:self.hasReadWidthConstraint];
    }
}

- (void)_updateStatusButtonWidthConstraint
{
    if (_statusButton) {
        [self removeConstraint:self.statusWidthConstraint];
        
        self.statusWidthConstraint = [NSLayoutConstraint constraintWithItem:self.statusButton attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:0 constant:self.statusSize];
        [self addConstraint:self.statusWidthConstraint];
    }
}

- (void)_updateActivityWidthConstraint
{
    if (_activity) {
        [self removeConstraint:self.activtiyWidthConstraint];
        
        self.statusWidthConstraint = [NSLayoutConstraint constraintWithItem:self.activity attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:0 constant:self.activitySize];
        [self addConstraint:self.activtiyWidthConstraint];
    }
}

- (void)_updateBubbleMaxWidthConstraint
{
    [self removeConstraint:self.bubbleMaxWidthConstraint];
    //    self.bubbleMaxWidthConstraint.active = NO;
    
    self.bubbleMaxWidthConstraint = [NSLayoutConstraint constraintWithItem:self.bubbleView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationLessThanOrEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:self.bubbleMaxWidth];
    [self addConstraint:self.bubbleMaxWidthConstraint];
    //    self.bubbleMaxWidthConstraint.active = YES;
}

#pragma mark - setter

- (void)setModel:(id<IMessageModel>)model
{
    _model = model;
    if ([self respondsToSelector:@selector(isCustomBubbleView:)] && [self isCustomBubbleView:model]) {
        [self setCustomModel:model];
    } else {
        switch (model.bodyType) {
            case EMMessageBodyTypeText:
            {
                if ([model.message valueForKey:@"ext"]) {
                    // 名片
                    if([[model.message valueForKey:@"ext"] valueForKey:@"user_card"]){
                        
                        _bubbleView.firstName.text = [[[model.message valueForKey:@"ext"] valueForKey:@"user_name"] substringToIndex:1];
                        _bubbleView.nameLable.text = [[model.message valueForKey:@"ext"] valueForKey:@"user_name"];
                        NSString *phoneNO = [[model.message valueForKey:@"ext"] valueForKey:@"user_phone"];
                        phoneNO = [phoneNO stringByReplacingOccurrencesOfString:@"-" withString:@""];
                        phoneNO = [phoneNO stringByReplacingOccurrencesOfString:@" " withString:@""];
                        phoneNO = [phoneNO stringByReplacingOccurrencesOfString:@"+" withString:@""];
                        //如果是国际号码或者带着“＋”的特殊号码，需要特殊处理
                        if ([phoneNO hasPrefix:@"86"]) {
                            if ([phoneNO length]==13) {//大陆手机号
                                phoneNO = [phoneNO substringFromIndex:([phoneNO length] -11)];
                            }else {
                                phoneNO = [phoneNO substringFromIndex:2];//以“＋86”开头的国际电话号
                            }
                        }
                        NSMutableAttributedString *ms = [[NSMutableAttributedString alloc] initWithString:phoneNO];
                        NSDictionary *attr = @{NSForegroundColorAttributeName:[UIColor blueColor], NSUnderlineStyleAttributeName:@(1)};
                        [ms addAttributes:attr range:NSMakeRange(0, [ms length])];
                        _bubbleView.phoneNum.attributedText = ms;
                    }
                    // 系统消息
                    else if ([[model.message valueForKey:@"ext"] valueForKey:@"robot_msg_type"])
                    {
                        NSString *msg_type =[[model.message valueForKey:@"ext"] valueForKey:@"robot_msg_type"];
                        // 公告
                        if ([msg_type isEqualToString:@"announcement"])
                        {
                            _bubbleView.msgType.text = [NSString stringWithFormat:@"%@发布了新公告",[model.message valueForKeyPath:@"ext.data.SENDNAME"]];
                            _bubbleView.msgTitle.text = [model.message valueForKeyPath:@"ext.data.NAME"];
                            _bubbleView.msgContent.text = [model.message valueForKeyPath:@"ext.data.DESC"];
                            NSMutableAttributedString *ms = [[NSMutableAttributedString alloc] initWithString:@"查看公告"];
                            NSDictionary *attr = @{NSForegroundColorAttributeName:[UIColor blueColor], NSUnderlineStyleAttributeName:@(1)};
                            [ms addAttributes:attr range:NSMakeRange(0, [ms length])];
                            _bubbleView.msgReadMore.attributedText = ms;
                        }
                        // 任务
//                        else if([msg_type isEqualToString:@"task"])
//                        {
//                            if ([[model.message valueForKeyPath:@"ext.data.ACTION"] isEqualToString:@"publish"]) {
//                                _bubbleView.msgType.text = [NSString stringWithFormat:@"%@发布了新任务",[model.message valueForKeyPath:@"ext.data.CREATENAME"]];
//                                NSMutableAttributedString *ms = [[NSMutableAttributedString alloc] initWithString:@"查看任务"];
//                                NSDictionary *attr = @{NSForegroundColorAttributeName:HXSystemColor, NSUnderlineStyleAttributeName:@(1)};
//                                [ms addAttributes:attr range:NSMakeRange(0, [ms length])];
//                                _bubbleView.msgReadMore.attributedText = ms;
//                                
//                            }
//                            else if ([[model.message valueForKeyPath:@"ext.data.ACTION"] isEqualToString:@"finish"])
//                            {
//                                _bubbleView.msgType.text = [NSString stringWithFormat:@"%@完成任务",[model.message valueForKeyPath:@"ext.data.CREATENAME"]];
//                                NSMutableAttributedString *ms = [[NSMutableAttributedString alloc] initWithString:@"查看任务"];
//                                NSDictionary *attr = @{NSForegroundColorAttributeName:HXSystemColor, NSUnderlineStyleAttributeName:@(1)};
//                                [ms addAttributes:attr range:NSMakeRange(0, [ms length])];
//                                _bubbleView.msgReadMore.attributedText = ms;
//                                
//                            }
//                            else if ([[model.message valueForKeyPath:@"ext.data.ACTION"] isEqualToString:@"cancel"])
//                            {
//                                _bubbleView.msgType.text = [NSString stringWithFormat:@"%@撤销任务",[model.message valueForKeyPath:@"ext.data.CREATENAME"]];
//                                NSDate *datetime = [NSDate dateWithTimeIntervalSince1970:(model.message.timestamp-1)/1000];
//                                NSString*date= [ToolHelper stringFromDate:datetime format:@"yyyy-MM-dd HH:mm"];
//                                _bubbleView.msgReadMore.text  = date;
//                                _bubbleView.msgReadMore.textColor = [UIColor lightGrayColor];
//                            }
//                            _bubbleView.msgTitle.text = [model.message valueForKeyPath:@"ext.data.NAME"];
//                            _bubbleView.msgContent.text = [model.message valueForKeyPath:@"ext.data.CONTENT"];
//                        }
//                        // 请假
//                        else if([msg_type isEqualToString:@"holiday"])
//                        {
//                            _bubbleView.msgType.text =  [NSString stringWithFormat:@"%@的请假单",[model.message valueForKeyPath:@"ext.data.USERNAME"]];
//                            _bubbleView.msgStartDate.text = [model.message valueForKeyPath:@"ext.data.BEGINDATE"];
//                            _bubbleView.msgEndDate.text = [model.message valueForKeyPath:@"ext.data.ENDDATE"];
//                            _bubbleView.msgBody.text = [model.message valueForKeyPath:@"ext.data.CONTENT"];
//                            _bubbleView.msgLeaveType.text = [NSString stringWithFormat:@"%@:",[model.message valueForKeyPath:@"ext.data.TYPENAME"]];
//                            
//                            NSDate *startDate = [ToolHelper dateFromString:_bubbleView.msgStartDate.text format:@"yyyy-MM-dd HH:mm"];
//                            NSTimeInterval start = [startDate timeIntervalSince1970];
//                            NSDate *endDate = [ToolHelper dateFromString:_bubbleView.msgEndDate.text format:@"yyyy-MM-dd HH:mm"];
//                            NSTimeInterval end = [endDate timeIntervalSince1970];
//                            NSTimeInterval timeDifference = end - start;
//                            
//                            NSInteger day =timeDifference/86400;
//                            NSInteger hour = ((long long)timeDifference % 86400)/3600;
//                            NSInteger minute = (((long long)timeDifference % 86400) % 3600)/60;
//                            if (day)
//                                _bubbleView.msgLeaveTime.text = [NSString stringWithFormat:@"%ld天%.1f小时",(long)day,hour + minute/60.];
//                            else
//                                _bubbleView.msgLeaveTime.text = [NSString stringWithFormat:@"%.1f小时",hour + minute/60.];
//                            if ([model.text rangeOfString:@"新增"].length > 0)
//                                _bubbleView.msgProgress.text = @"待处理";
//                            else
//                                _bubbleView.msgProgress.text = @"已处理";
//                        }
                    }
                    else if([[model.message valueForKey:@"ext"] valueForKey:@"is_voice_call"] || [[model.message valueForKey:@"ext"] valueForKey:@"is_video_call"])
                    {
                        _bubbleView.textLabel.attributedText = [[EaseEmotionEscape sharedInstance] attStringFromTextForChatting:model.text textFont:self.messageTextFont];
                    }
                    //文本转发
                    else if ([[model.message valueForKey:@"ext"] valueForKey:MESSAGE_TRANSMIT]) {
                        _bubbleView.textLabel.attributedText = [[EaseEmotionEscape sharedInstance] attStringFromTextForChatting:model.text textFont:self.messageTextFont];

//                        NSLog(@"ext:%@",[model.message valueForKey:@"ext"]);
//                        //对封装的气泡的属性赋值
//                        _bubbleView.tmTextLabel.attributedText = [[EaseEmotionEscape sharedInstance] attStringFromTextForChatting:model.text textFont:self.messageTextFont];
//                        _bubbleView.tmlittleTextLabel.attributedText = [[EaseEmotionEscape sharedInstance] attStringFromTextForChatting:model.text textFont:self.messageTextFont];
//
//                        NSString *fromName = [[model.message valueForKey:@"ext"] objectForKey:MESSAGE_FROM_ID];
//                        DDUserEntity *User = [[RuntimeStatus instance] GetUserForName:fromName];
//                        _bubbleView.tmFromNameLabel.text = User.nick;
//                        _bubbleView.tmNameLabel.text = User.nick;
//
//                        _bubbleView.firstName.text = [User.nick substringToIndex:1];
//                        _bubbleView.lineImg.image = [UIImage imageNamed:@"HuanXin.bundle/transmittext_line2"];
//                        
//                        //time:换算成北京时间
//                        NSString *timeStr = [[model.message valueForKey:@"ext"] objectForKey:MESSAGE_FROM_TIME];
//                        long long timeStemp = [timeStr doubleValue];
//                        _bubbleView.tmTimelabel.text = [TimeTool timeStr:timeStemp];
                    }
                }
                else
                {
                    _bubbleView.textLabel.attributedText = [[EaseEmotionEscape sharedInstance] attStringFromTextForChatting:model.text textFont:self.messageTextFont];
                }
            }
                break;
            case EMMessageBodyTypeImage:
            {
                UIImage *image = _model.thumbnailImage;
                if (!image) {
                    image = _model.image;
                    if (!image) {
                        [_bubbleView.imageView sd_setImageWithURL:[NSURL URLWithString:_model.fileURLPath] placeholderImage:[UIImage imageNamed:_model.failImageName]];
                    } else {
                        _bubbleView.imageView.image = image;
                    }
                } else {
                    _bubbleView.imageView.image = image;
                }
            }
                break;
            case EMMessageBodyTypeLocation:
            {
                _bubbleView.locationLabel.text = _model.address;
            }
                break;
            case EMMessageBodyTypeVoice:
            {
                if (_bubbleView.voiceImageView) {
//                    if ([self.sendMessageVoiceAnimationImages count] > 0 && [self.recvMessageVoiceAnimationImages count] > 0) {
//                        self.bubbleView.voiceImageView.image = self.model.isSender ?[self.sendMessageVoiceAnimationImages objectAtIndex:0] : [self.recvMessageVoiceAnimationImages objectAtIndex:0];
//                    }
                    self.bubbleView.voiceImageView.image = self.model.isSender ? [UIImage imageNamed:@"HuanXin.bundle/chat_sender_audio_playing_full"] : [UIImage imageNamed:@"HuanXin.bundle/chat_receiver_audio_playing_full"];
                    _bubbleView.voiceImageView.animationImages = self.model.isSender ? self.sendMessageVoiceAnimationImages:self.recvMessageVoiceAnimationImages;
                }
                if (!self.model.isSender) {
                    if (self.model.isMediaPlayed){
                        _bubbleView.isReadView.hidden = YES;
                    } else {
                        _bubbleView.isReadView.hidden = NO;
                    }
                }
                
                if (_model.isMediaPlaying) {
                    [_bubbleView.voiceImageView startAnimating];
                }
                else{
                    [_bubbleView.voiceImageView stopAnimating];
                }
                
                _bubbleView.voiceDurationLabel.text = [NSString stringWithFormat:@"%d''",(int)_model.mediaDuration];
            }
                break;
            case EMMessageBodyTypeVideo:
            {
                UIImage *image = _model.isSender ? _model.image : _model.thumbnailImage;
                if (!image) {
                    image = _model.image;
                    if (!image) {
                        [_bubbleView.videoImageView sd_setImageWithURL:[NSURL URLWithString:_model.fileURLPath] placeholderImage:[UIImage imageNamed:_model.failImageName]];
                    } else {
                        _bubbleView.videoImageView.image = image;
                    }
                } else {
                    _bubbleView.videoImageView.image = image;
                }
            }
                break;
            case EMMessageBodyTypeFile:
            {
                _bubbleView.fileIconView.image = [UIImage imageNamed:_model.fileIconName];
                _bubbleView.fileNameLabel.text = _model.fileName;
                _bubbleView.fileSizeLabel.text = _model.fileSizeDes;
            }
                break;
            default:
                break;
        }
    }
}

- (void)setStatusSize:(CGFloat)statusSize
{
    _statusSize = statusSize;
    [self _updateStatusButtonWidthConstraint];
}

- (void)setActivitySize:(CGFloat)activitySize
{
    _activitySize = activitySize;
    [self _updateActivityWidthConstraint];
}

- (void)setSendBubbleBackgroundImage:(UIImage *)sendBubbleBackgroundImage
{
    _sendBubbleBackgroundImage = sendBubbleBackgroundImage;
}

- (void)setRecvBubbleBackgroundImage:(UIImage *)recvBubbleBackgroundImage
{
    _recvBubbleBackgroundImage = recvBubbleBackgroundImage;
}

- (void)setBubbleMaxWidth:(CGFloat)bubbleMaxWidth
{
    _bubbleMaxWidth = bubbleMaxWidth;
    [self _updateBubbleMaxWidthConstraint];
}

- (void)setRightBubbleMargin:(UIEdgeInsets)rightBubbleMargin
{
    switch (_messageType) {
            case EMMessageBodyTypeImage:
            case EMMessageBodyTypeLocation:
                _rightBubbleMargin = UIEdgeInsetsMake(2, 3, 3, 8);
                break;
            default:
            _rightBubbleMargin = rightBubbleMargin;
                break;
        }
}

- (void)setLeftBubbleMargin:(UIEdgeInsets)leftBubbleMargin
{
        switch (_messageType) {
            case EMMessageBodyTypeImage:
            case EMMessageBodyTypeLocation:
                _leftBubbleMargin = UIEdgeInsetsMake(2, 8, 3, 3);
                break;
            default:
                _leftBubbleMargin = leftBubbleMargin;
                break;
        }
}

- (void)setBubbleMargin:(UIEdgeInsets)bubbleMargin
{
    _bubbleMargin = bubbleMargin;
    _bubbleMargin = self.model.isSender ? _rightBubbleMargin:_leftBubbleMargin;
    if ([self respondsToSelector:@selector(isCustomBubbleView:)] && [self isCustomBubbleView:_model]) {
        [self updateCustomBubbleViewMargin:_bubbleMargin model:_model];
    } else {
        if (_bubbleView) {
            switch (_messageType) {
                case EMMessageBodyTypeText:
                {
                    // Card
                    if ([_model.message valueForKey:@"ext"]) {
                        if([[_model.message valueForKey:@"ext"] valueForKey:@"user_card"]){
                            [_bubbleView updateCardMargin:_bubbleMargin];
                        }
                        else if([[_model.message valueForKey:@"ext"] valueForKey:@"robot_msg_type"])
                        {
                            NSString *msg_type =[[_model.message valueForKey:@"ext"] valueForKey:@"robot_msg_type"];
                            // announcement 公告  holiday  请假  task  任务
                            if ([msg_type isEqualToString:@"announcement"]
//                                ||[msg_type isEqualToString:@"task"]
                                )
                            {
                                [_bubbleView updateTaskMargin:_bubbleMargin];
                            }
//                            else if([msg_type isEqualToString:@"holiday"])
//                            {
//                                // coding
//                                [_bubbleView updateLeaveMargin:_bubbleMargin];
//                            }
                        }
                        else if([[_model.message valueForKey:@"ext"] valueForKey:@"is_voice_call"] || [[_model.message valueForKey:@"ext"] valueForKey:@"is_video_call"])
                        {
                            [_bubbleView updateTextMargin:_bubbleMargin];
                        }
                        //转发
                        else if ([[_model.message valueForKey:@"ext"] valueForKey:MESSAGE_TRANSMIT]){
                            [_bubbleView updateTextMargin:_bubbleMargin];
//                            [_bubbleView updateTransmitTextMargin:_bubbleMargin];
                        }

                    }
                    else
                        [_bubbleView updateTextMargin:_bubbleMargin];
                }
                    break;
                case EMMessageBodyTypeImage:
                {
                    [_bubbleView updateImageMargin:_bubbleMargin];
                }
                    break;
                case EMMessageBodyTypeLocation:
                {
                    [_bubbleView updateLocationMargin:_bubbleMargin];
                }
                    break;
                case EMMessageBodyTypeVoice:
                {
                    [_bubbleView updateVoiceMargin:_bubbleMargin];
                }
                    break;
                case EMMessageBodyTypeVideo:
                {
                    [_bubbleView updateVideoMargin:_bubbleMargin];
                }
                    break;
                case EMMessageBodyTypeFile:
                {
                    [_bubbleView updateFileMargin:_bubbleMargin];
                }
                    break;
                default:
                    break;
            }
            
        }
    }
}

- (void)setMessageTextFont:(UIFont *)messageTextFont
{
    _messageTextFont = messageTextFont;
    if (_bubbleView.textLabel) {
        _bubbleView.textLabel.font = messageTextFont;
    }
}

- (void)setMessageTextColor:(UIColor *)messageTextColor
{
    _messageTextColor = messageTextColor;
    if (_bubbleView.textLabel) {
        _bubbleView.textLabel.textColor = _messageTextColor;
    }
}

- (void)setMessageLocationColor:(UIColor *)messageLocationColor
{
    _messageLocationColor = messageLocationColor;
    if (_bubbleView.locationLabel) {
        _bubbleView.locationLabel.textColor = _messageLocationColor;
    }
}

- (void)setMessageLocationFont:(UIFont *)messageLocationFont
{
    _messageLocationFont = messageLocationFont;
    if (_bubbleView.locationLabel) {
        _bubbleView.locationLabel.font = _messageLocationFont;
    }
}

- (void)setSendMessageVoiceAnimationImages:(NSArray *)sendMessageVoiceAnimationImages
{
    _sendMessageVoiceAnimationImages = sendMessageVoiceAnimationImages;
}

- (void)setRecvMessageVoiceAnimationImages:(NSArray *)recvMessageVoiceAnimationImages
{
    _recvMessageVoiceAnimationImages = recvMessageVoiceAnimationImages;
}

- (void)setMessageVoiceDurationColor:(UIColor *)messageVoiceDurationColor
{
    _messageVoiceDurationColor = messageVoiceDurationColor;
    if (_bubbleView.voiceDurationLabel) {
        _bubbleView.voiceDurationLabel.textColor = _messageVoiceDurationColor;
    }
}

- (void)setMessageVoiceDurationFont:(UIFont *)messageVoiceDurationFont
{
    _messageVoiceDurationFont = messageVoiceDurationFont;
    if (_bubbleView.voiceDurationLabel) {
        _bubbleView.voiceDurationLabel.font = _messageVoiceDurationFont;
    }
}

- (void)setMessageFileNameFont:(UIFont *)messageFileNameFont
{
    _messageFileNameFont = messageFileNameFont;
    if (_bubbleView.fileNameLabel) {
        _bubbleView.fileNameLabel.font = _messageFileNameFont;
    }
}

- (void)setMessageFileNameColor:(UIColor *)messageFileNameColor
{
    _messageFileNameColor = messageFileNameColor;
    if (_bubbleView.fileNameLabel) {
        _bubbleView.fileNameLabel.textColor = _messageFileNameColor;
    }
}

- (void)setMessageFileSizeFont:(UIFont *)messageFileSizeFont
{
    _messageFileSizeFont = messageFileSizeFont;
    if (_bubbleView.fileSizeLabel) {
        _bubbleView.fileSizeLabel.font = _messageFileSizeFont;
    }
}

- (void)setMessageFileSizeColor:(UIColor *)messageFileSizeColor
{
    _messageFileSizeColor = messageFileSizeColor;
    if (_bubbleView.fileSizeLabel) {
        _bubbleView.fileSizeLabel.textColor = _messageFileSizeColor;
    }
}

#pragma mark - action

- (void)bubbleViewTapAction:(UITapGestureRecognizer *)tapRecognizer
{
    if (tapRecognizer.state == UIGestureRecognizerStateEnded) {
        if (!_delegate) {
            return;
        }
        
        if ([self respondsToSelector:@selector(isCustomBubbleView:)] && [self isCustomBubbleView:_model]) {
            if ([_delegate respondsToSelector:@selector(messageCellSelected:)]) {
                [_delegate messageCellSelected:_model];
                return;
            }
        }
        switch (_model.bodyType) {
            case EMMessageBodyTypeText:
            {
                if ([_delegate respondsToSelector:@selector(messageCellSelected:)]) {
                    [_delegate messageCellSelected:_model];
                }
            }
                break;
            case EMMessageBodyTypeImage:
            {
                if ([_delegate respondsToSelector:@selector(messageCellSelected:)]) {
                    [_delegate messageCellSelected:_model];
                }
            }
                break;
            case EMMessageBodyTypeLocation:
            {
                if ([_delegate respondsToSelector:@selector(messageCellSelected:)]) {
                    [_delegate messageCellSelected:_model];
                }
            }
                break;
            case EMMessageBodyTypeVoice:
            {
                if ([_delegate respondsToSelector:@selector(messageCellSelected:)]) {
                    [_delegate messageCellSelected:_model];
                }
            }
                break;
            case EMMessageBodyTypeVideo:
            {
                if ([_delegate respondsToSelector:@selector(messageCellSelected:)]) {
                    [_delegate messageCellSelected:_model];
                }
            }
                break;
            case EMMessageBodyTypeFile:
            {
                if ([_delegate respondsToSelector:@selector(messageCellSelected:)]) {
                    [_delegate messageCellSelected:_model];
                }
            }
                break;
            default:
                break;
        }
    }
}

- (void)avatarViewTapAction:(UITapGestureRecognizer *)tapRecognizer
{
    if ([_delegate respondsToSelector:@selector(avatarViewSelcted:)]) {
        [_delegate avatarViewSelcted:_model];
    }
}

- (void)statusAction
{
    if ([_delegate respondsToSelector:@selector(statusButtonSelcted:withMessageCell:)]) {
        [_delegate statusButtonSelcted:_model withMessageCell:self];
    }
}

#pragma mark - IModelCell
/*
- (BOOL)isCustomBubbleView:(id<IMessageModel>)model
{
    return NO;
}

- (void)setCustomModel:(id<IMessageModel>)model
{

}

- (void)setCustomBubbleView:(id<IMessageModel>)model
{

}

- (void)updateCustomBubbleViewMargin:(UIEdgeInsets)bubbleMargin model:(id<IMessageModel>)model
{

}*/

#pragma mark - public

+ (NSString *)cellIdentifierWithModel:(id<IMessageModel>)model
{
    NSString *identifier = @"EaseMessageCell";
    NSString *cellIdentifier = nil;
    if (model.isSender) {
        identifier = [identifier stringByAppendingString:@"Send"];
        switch (model.bodyType) {
            case EMMessageBodyTypeText:
                if ([model.message valueForKey:@"ext"])
                {
                    if([[model.message valueForKey:@"ext"] valueForKey:@"user_card"])
                    {
                        cellIdentifier = [identifier stringByAppendingString:@"Ext_user_card"];
                    }
                    NSString *msg_type =[[model.message valueForKey:@"ext"] valueForKey:@"robot_msg_type"];
                    if ([msg_type isEqualToString:@"announcement"])
                        cellIdentifier = [identifier stringByAppendingString:@"Ext_notice"];
//                    else  if([msg_type isEqualToString:@"holiday"])
//                        cellIdentifier = [identifier stringByAppendingString:@"Ext_leavel"];
//                    else  if([msg_type isEqualToString:@"task"])
//                        cellIdentifier = [identifier stringByAppendingString:@"Ext_task"];
                    //文本转发
                    else if ([[model.message valueForKey:@"ext"] valueForKey:MESSAGE_TRANSMIT]){
                        cellIdentifier = EaseMessageCellIdentifierSendText;
//                        //因为转发气泡与普通气泡是不同的气泡，所以在设置cellIdentifier时，应区分，避免混用
//                        cellIdentifier = [identifier stringByAppendingString:@"Ext_transmit"];
                    }
                }
                else
                {
                    cellIdentifier = EaseMessageCellIdentifierSendText;
                }
                break;
            case EMMessageBodyTypeImage:
                cellIdentifier = EaseMessageCellIdentifierSendImage;
                break;
            case EMMessageBodyTypeVideo:
                cellIdentifier = EaseMessageCellIdentifierSendVideo;
                break;
            case EMMessageBodyTypeLocation:
                cellIdentifier = EaseMessageCellIdentifierSendLocation;
                break;
            case EMMessageBodyTypeVoice:
                cellIdentifier = EaseMessageCellIdentifierSendVoice;
                break;
            case EMMessageBodyTypeFile:
                cellIdentifier = EaseMessageCellIdentifierSendFile;
                break;
            default:
                break;
        }
    }
    else{
        switch (model.bodyType) {
            case EMMessageBodyTypeText:
                identifier = [identifier stringByAppendingString:@"Recv"];
                // Card
                if ([model.message valueForKey:@"ext"])
                {
                    if([[model.message valueForKey:@"ext"] valueForKey:@"user_card"])
                    {
                        cellIdentifier = [identifier stringByAppendingString:@"Ext_user_card"];
                    }
                    if([[model.message valueForKey:@"ext"] valueForKey:@"robot_msg_type"])
                    {
                        NSString *msg_type =[[model.message valueForKey:@"ext"] valueForKey:@"robot_msg_type"];
                        if ([msg_type isEqualToString:@"announcement"])
                            cellIdentifier = [identifier stringByAppendingString:@"Ext_notice"];
//                        else  if([msg_type isEqualToString:@"holiday"])
//                            cellIdentifier = [identifier stringByAppendingString:@"Ext_leavel"];
//                        else  if([msg_type isEqualToString:@"task"])
//                            cellIdentifier = [identifier stringByAppendingString:@"Ext_task"];
                        else if([[model.message valueForKey:@"ext"] valueForKey:@"is_voice_call"] || [[model.message valueForKey:@"ext"] valueForKey:@"is_video_call"])
                        {
                            cellIdentifier = EaseMessageCellIdentifierRecvText;
                        }
                        //文本转发
                        else if ([[model.message valueForKey:@"ext"] valueForKey:MESSAGE_TRANSMIT]) {
                            cellIdentifier = EaseMessageCellIdentifierRecvText;
                            //因为转发气泡与普通气泡是不同的气泡，所以在设置cellIdentifier时，应区分，避免混用
//                            cellIdentifier = [identifier stringByAppendingString:@"Ext_transmit"];
                        }
                    }
                }
                else
                {
                    cellIdentifier = EaseMessageCellIdentifierRecvText;
                }
                break;
            case EMMessageBodyTypeImage:
                cellIdentifier = EaseMessageCellIdentifierRecvImage;
                break;
            case EMMessageBodyTypeVideo:
                cellIdentifier = EaseMessageCellIdentifierRecvVideo;
                break;
            case EMMessageBodyTypeLocation:
                cellIdentifier = EaseMessageCellIdentifierRecvLocation;
                break;
            case EMMessageBodyTypeVoice:
                cellIdentifier = EaseMessageCellIdentifierRecvVoice;
                break;
            case EMMessageBodyTypeFile:
                cellIdentifier = EaseMessageCellIdentifierRecvFile;
                break;
            default:
                break;
        }
    }
    
    return cellIdentifier;
}

+ (CGFloat)cellHeightWithModel:(id<IMessageModel>)model
{
    if (model.cellHeight > 0) {
        return model.cellHeight;
    }
    
    EaseMessageCell *cell = [self appearance];
    CGFloat bubbleMaxWidth = cell.bubbleMaxWidth;
    if ([UIDevice currentDevice].systemVersion.floatValue == 7.0) {
        bubbleMaxWidth = 200;
    }
    bubbleMaxWidth -= (cell.leftBubbleMargin.left + cell.leftBubbleMargin.right + cell.rightBubbleMargin.left + cell.rightBubbleMargin.right)/2;
    
    CGFloat height = EaseMessageCellPadding + cell.bubbleMargin.top + cell.bubbleMargin.bottom;
    
    switch (model.bodyType) {
        case EMMessageBodyTypeText:
        {
            if ([model.message valueForKey:@"ext"]) {
                if ([[model.message valueForKey:@"ext"] valueForKey:@"user_card"])
                    height += 40;
                NSString *msg_type =[[model.message valueForKey:@"ext"] valueForKey:@"robot_msg_type"];
                // announcement 公告  holiday  请假  task  任务
                if ([msg_type isEqualToString:@"announcement"]
//                    ||[msg_type isEqualToString:@"task"]
                    )
                    height += 116;
//                if([msg_type isEqualToString:@"holiday"])
//                {
//                    NSDictionary *attributs = @{NSFontAttributeName:systemFont(14)};
//                    CGRect bounds = [[model.message valueForKeyPath:@"ext.data.CONTENT"]  boundingRectWithSize:CGSizeMake(200, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributs context:nil];
//                    if (bounds.size.height>height) {
//                        height += 133 ;
//                    }
//                    else
//                    {
//                        height += 115;
//                    }
//                }
                if([[model.message valueForKey:@"ext"] valueForKey:@"is_voice_call"] || [[model.message valueForKey:@"ext"] valueForKey:@"is_video_call"])
                {
                    NSAttributedString *text = [[EaseEmotionEscape sharedInstance] attStringFromTextForChatting:model.text textFont:cell.messageTextFont];
                    CGRect rect = [text boundingRectWithSize:CGSizeMake(bubbleMaxWidth, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading context:nil];
                    height += (rect.size.height > 20 ? rect.size.height : 20) + 10;
                }
                //文本转发
                else if ([[model.message valueForKey:@"ext"] valueForKey:MESSAGE_TRANSMIT]){
                    NSAttributedString *text = [[EaseEmotionEscape sharedInstance] attStringFromTextForChatting:model.text textFont:cell.messageTextFont];
                    CGRect rect = [text boundingRectWithSize:CGSizeMake(bubbleMaxWidth, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading context:nil];
                    height += (rect.size.height > 20 ? rect.size.height : 20) + 10;
//                    //计算文本的高度
//                    //15号字体的高度
//                    NSAttributedString *text1 = [[EaseEmotionEscape sharedInstance] attStringFromTextForChatting:model.text textFont:cell.messageTextFont];
//                    CGRect rect1 = [text1 boundingRectWithSize:CGSizeMake(bubbleMaxWidth, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading context:nil];
//
//                    //13号字体的高度
//                    NSAttributedString *text2 = [[EaseEmotionEscape sharedInstance] attStringFromTextForChatting:model.text textFont:systemFont(13)];
//                    //55=13-2-1.5+40+4；
//                    CGRect rect2 = [text2 boundingRectWithSize:CGSizeMake(bubbleMaxWidth-53.5, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading context:nil];
//                    height += rect1.size.height+20+3+20 +rect2.size.height+10;
                }
                
            }
        else
            {
                NSAttributedString *text = [[EaseEmotionEscape sharedInstance] attStringFromTextForChatting:model.text textFont:cell.messageTextFont];
                CGRect rect = [text boundingRectWithSize:CGSizeMake(bubbleMaxWidth, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading context:nil];
                height += (rect.size.height > 20 ? rect.size.height : 20) + 10;
            }
        }
            break;
        case EMMessageBodyTypeImage:
        case EMMessageBodyTypeVideo:
        {
            CGSize retSize = model.thumbnailImageSize;
            if (retSize.width == 0 || retSize.height == 0) {
                retSize.width = kEMMessageImageSizeWidth;
                retSize.height = kEMMessageImageSizeHeight;
            }
            else if (retSize.width > retSize.height) {
                CGFloat height =  kEMMessageImageSizeWidth / retSize.width * retSize.height;
                retSize.height = height;
                retSize.width = kEMMessageImageSizeWidth;
            }
            else {
                CGFloat width = kEMMessageImageSizeHeight / retSize.height * retSize.width;
                retSize.width = width;
                retSize.height = kEMMessageImageSizeHeight;
            }

            height += retSize.height;
        }
            break;
        case EMMessageBodyTypeLocation:
        {
            height += kEMMessageLocationHeight;
        }
            break;
        case EMMessageBodyTypeVoice:
        {
            height += kEMMessageVoiceHeight;
        }
            break;
        case EMMessageBodyTypeFile:
        {
            NSString *text = model.fileName;
            UIFont *font = cell.messageFileNameFont;
            CGRect nameRect;
            if ([NSString instancesRespondToSelector:@selector(boundingRectWithSize:options:attributes:context:)]) {
                nameRect = [text boundingRectWithSize:CGSizeMake(bubbleMaxWidth, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:font} context:nil];
            } else {
                nameRect.size = [text sizeWithFont:font constrainedToSize:CGSizeMake(bubbleMaxWidth, CGFLOAT_MAX) lineBreakMode:NSLineBreakByCharWrapping];
            }
            height += (nameRect.size.height > 20 ? nameRect.size.height : 20);
            
            text = model.fileSizeDes;
            font = cell.messageFileSizeFont;
            CGRect sizeRect;
            if ([NSString instancesRespondToSelector:@selector(boundingRectWithSize:options:attributes:context:)]) {
                sizeRect = [text boundingRectWithSize:CGSizeMake(bubbleMaxWidth, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:font} context:nil];
            } else {
                sizeRect.size = [text sizeWithFont:font constrainedToSize:CGSizeMake(bubbleMaxWidth, CGFLOAT_MAX) lineBreakMode:NSLineBreakByCharWrapping];
            }
            height += (sizeRect.size.height > 15 ? sizeRect.size.height : 15);
        }
            break;
        default:
            break;
    }

    height += EaseMessageCellPadding;
    model.cellHeight = height;
    
    return height;
}

@end
